package com.changgou.seckill.web.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.seckill.feign.SeckillOrderFeign;
import com.changgou.seckill.web.aspect.AccessLimit;
import com.changgou.seckill.web.util.CookieUtil;
import com.changgou.util.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author kfzhao
 * @version 1.0
 * @className SeckillOrderController
 * @description
 * @date 2022/1/6 2:49
 */
@RestController
@RequestMapping("/wseckillorder")
public class SeckillOrderController {

    @Autowired
    private SeckillOrderFeign seckillOrderFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/add")
    @AccessLimit
    public Result add(@RequestParam("time") String time, @RequestParam("id") Long id, String random) {

        String redisRandomCode = (String) redisTemplate.opsForValue().get("randomcode_" + readCookie());
        if (StringUtils.isEmpty(redisRandomCode)) {
            return new Result(false, StatusCode.ERROR, "下单失败");
        }
        if (!random.equals(redisRandomCode)) {
            return new Result(false, StatusCode.ERROR, "下单失败");
        }

        return seckillOrderFeign.add(time, id);
    }

    /**
     * 获取随机字符串
     *
     * @param
     * @return java.lang.String
     * @throws
     * @description
     * @author kfzhao
     * @date 2022/1/7 2:27
     */
    @GetMapping("/getToken")
    @ResponseBody
    public String getToken() {
        String randomString = RandomUtil.getRandomString();
        String cookie = readCookie();
        redisTemplate.opsForValue().set("randomcode_" + cookie, randomString, 5, TimeUnit.SECONDS);
        return randomString;
    }

    /**
     * 通过cookie获取jti
     *
     * @param
     * @return java.lang.String
     * @throws
     * @description
     * @author kfzhao
     * @date 2022/1/7 2:35
     */
    private String readCookie() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String jti = CookieUtil.readCookie(request, "uid").get("uid");
        return jti;
    }

}
